<template>
	<view >
		<view @click="tosmiao">
			前往导航
		</view>
		<view class="list-item"><text @click="startAddress">起始地点：{{startPoint.name}}</text></view>
		<view class="list-item"><text @click="endAddress">目的地：{{endPoint.name}}</text></view>
		
		<view class="list-item" v-if="startPoint.name && endPoint.name">
			<text >路程：{{distance}}公里 时间：{{duration}}分钟</text>
			<view   >
				<view>
					车辆类型
				</view>
				<radio-group  @change="radioCar">
				      <label class="carType" v-for="(item, index) in radioOptions" :key="index">
				        <radio :value="item.value" :checked="radioValue == item.value">{{ item.label }}</radio>
				      </label>
					  {{radioValue}}
				</radio-group>
			</view>
			<view v-if="radioValue != 0">
				<view>
					用车方式
				</view>
				<radio-group  @change="useCar">
				      <label class="useCar" v-for="(item, index) in useCarType" :key="index">
				        <radio :value="item.value" >{{ item.label }}</radio>
				      </label>
				    </radio-group>
			</view>
			<view v-if="useCarValue == 1">
				<view>
					是否预约
				</view>
				<radio-group @change="appointmentCar">
				      <label class="appointment" v-for="(item, index) in appointmentType" :key="index">
				        <radio :value="item.value">{{ item.label }}</radio>
				      </label>
				    </radio-group>
			</view>
			<view  v-if="appointmentValue!=2" >
				<picker mode="date" :value="date" start="2020-01-01" end="2030-12-31" @change="onDateChange">
				      <view class="picker">
				        当前选择的日期：{{ date }}
				      </view>
				    </picker>
			</view>
			<view v-if="endPoint.name" @click="submitToDriver" class="send-btn">
				发送给司机
			</view>
		</view>
	</view>
	
	
	
  <view class="map-container">
    <map id="map" :latitude="startPoint.latitude" :longitude="startPoint.longitude" :polyline="polyline" 
	:markers="markers" style="width: 100%; height: 80%;" :scale="16"
      :show-location="true"
     ></map>
  </view>


</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import amapWx from '@/static/amap-wx.130.js'; // 引入高德地图SDK
				
	const date =ref(new Date().getDate())
	const radioOptions=ref( [
			{ label: '新能源', value: '1' },
			{ label: '舒适型', value: '2' },
			{ label: '豪华型', value: '3' },
			{ label: '商务型', value: '4' }
	])
	const useCarType =ref( [
				        { label: '普通叫车', value: '1' },
				        { label: '半日租', value: '2' },
				        { label: '日租', value: '3' },
	])
	
	const appointmentType=ref([
				        { label: '预约叫车', value: '1' },
				        { label: '实用叫车', value: '2' }
				])

    const map = ref(null);
    const myAmapFunT = ref(null);
	
	const radioValue=ref(1)
	const useCarValue=ref(1)
	const appointmentValue=ref(2)
	
	const markers =ref([])
	const startPoint=ref( {
		latitude: 26.56045894387685, //纬度
		longitude: 106.68005128661751, //经度
		name: '',
		address: ''
	})
	const endPoint=ref({
		latitude: 0, //纬度
		longitude: 0, //经度
		name: '',
		address: ''
	})
	const showLocationPicker=ref(false) 
	const selectedLongitude =ref(0)
	const selectedLatitude =ref(0)
	const mapCtx=ref(null)
	const polyline=ref(null)
	const distance=ref("")
	const duration=ref("")

    onMounted(() => {
		myAmapFunT.value = new amapWx.AMapWX({
			//把这个key换成你自己的1
			key:"d4a7ff001e08634bdd5a79e306e3298f"
		})
		getCurrentLocation();
      map.value = new amapWx.AMapWX({
        key: '1ecb10ee8837f9a355719170286d5e3e'
      });
      // 初始化地图实例等操作
    });
	
	
 	const tosmiao=()=>{
	uni.navigateTo({
		url:"/pages/index/smiao"
	})
	}
	
	const submitToDriver=()=>{
		console.log("123")
		
		var order = {
			"depLongitude":startPoint.value.longitude,
			"depLatitude":startPoint.value.latitude,
			"destLongitude":endPoint.value.longitude,
			"destLatitude":endPoint.value.latitude,
			"expectDistance":distance.value,
			"estimatedDuration":duration.value,
			"carType":radioValue.value,
			"vehicleType":useCarValue.value,
			"isReserve":appointmentValue.value,
			"departTime":date.value,
			"destination":endPoint.value.name,
			"departure":startPoint.value.name
		}
		
		uni.request({
			url:"http://localhost:9201/test/add",
			method:"POST",
			data:order,
			success(res) {
				 console.log('Success:', res.data);
			},
			fail(err) {
				 console.error('Error:', err);
			}
		})
		
	}
	
	const onDateChange = (e) => {
	  date.value = e.target.value;
	};
	
	const radioCar=(evt)=>{
		console.log("sad"+JSON.stringify(evt.target.value))
		for(let i = 0;i<radioOptions.value.length;i++){
			if(radioOptions.value[i].value === evt.target.value){
				radioValue.value=radioOptions.value[i].value
				break
			}
		}
	}
	
	const useCar=(evt)=>{
		console.log("sadj j"+evt.target.value)
		for(let i = 0;i<useCarType.value.length;i++){
			if(useCarType.value[i].value === evt.target.value){
				useCarValue.value=useCarType.value[i].value
				break
			}
		}
	}
	
	const appointmentCar=(evt)=>{
		console.log("sad"+JSON.stringify(evt.target.value))
		for(let i = 0;i<appointmentType.value.length;i++){
			if(appointmentType.value[i].value === evt.target.value){
				appointmentValue.value=appointmentType.value[i].value
				break
			}
		}
	}
	
	//获取当前定位
	const getCurrentLocation=()=> {
		uni.getLocation({
			type: 'gcj02',
			success: function(res) {
				// console.log('当前：' , res);
				// console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
				startPoint.value.longitude = res.longitude;
				startPoint.value.latitude = res.latitude;
	 
				getAddress(startPoint.value.longitude + ',' +startPoint.value.latitude)
			}
		});
	}
	const flag =ref(10)

// 解析地址
	const getAddress=(loc)=> {
	
				var myAmapFun = myAmapFunT.value;
				if (loc !== null && loc !== '' && loc !== undefined) {
					myAmapFun.getRegeo({
						iconPath: 'http://img.wisdomtaxi.com/amap_icon.png',
						width: '37.5rpx',
						height: '37.5rpx',
						location: loc,
						success: function(data) { //成功回调
							// console.log('地址解析',data)
							startPoint.value.name = data[0].name
							startPoint.value.address = data[0].desc
 
							initMap()
						},
						fail: function(info) { //失败回调
							console.log(info)
						},
					});
				}
			}
	//初始化地图数据
	const initMap=()=> {
		markers.value.push({
			id: 1,
			latitude: startPoint.value.latitude, //纬度
			longitude:startPoint.value.longitude, //经度
			iconPath: '/static/images/home/start.png', //显示的图标
			rotate: 0, // 旋转度数
			width: 30, //宽
			height: 30, //高
			title:startPoint.value.name, //标注点名
			// alpha: 0.5, //透明度
			joinCluster: true,
			customCallout: {
				anchorY: 0,
				anchorX: 0,
				display: "ALWAYS",
			},
		}, )
	 
	}
	
	const startAddress=(opt)=>{
		// uni.openLocation({
		//   latitude: Number(startPoint.value.latitude),
		//   longitude: Number(startPoint.value.longitude),
		//   name: startPoint.value.name, // 地点名称
		//   address: startPoint.value.address, // 详细地址
		//   success() {
		//     console.log('地图打开成功');
		//   }
		// });
		//       // 地图点击事件
		//       selectedLatitude.value = e.latitude;
		//       selectedLongitude.value = e.longitude;
		//       showLocationPicker.value = true;
		uni.chooseLocation({
			latitude: opt?.latitude || startPoint.value.latitude,
			longitude: opt?.longitude || startPoint.value.longitude,
			success: function(res) {
				// console.log(res)
				// console.log('位置名称：' + res.name);
				// console.log('详细地址：' + res.address);
				// console.log('纬度：' + res.latitude);
				// console.log('经度：' + res.longitude);
				if (!res.name) {
					return uni.showToast({
						title: '请重新选择位置',
						icon: 'none'
					});
				}
				//设置终点
				startPoint.value = {
					longitude: res.longitude,
					latitude: res.latitude,
					name: res.name,
					address: res.address
				}
			},
			fail: function(info) { //失败回调
				console.log('调取失败')
				console.log(info)
			},
		})
		getCurrentLocation();
		var map = new amapWx.Map('container', {
		  zoom: 14, // 初始化缩放级别
		  center: [your_latitude, your_longitude], // 经纬度位置
		});
		var marker = new amapWx.Marker({
		  position: [latitude, longitude], // 用户坐标
		  icon: { // 图标配置
		    url: 'path/to/your/icon.png', // 图标路径
		    size: new amapWx.Size(32, 32), // 图标尺寸
		    offset: new amapWx.Pixel(-16, -16) // 图标偏移量，通常用于调整中心点
		  }
		});
		marker.setMap(map); // 添加到当前地图实例
		marker.addEventListener('click', function() {
		  // 这里可以添加你的处理逻辑
		});
		
	}
	const endAddress=(opt)=>{
		uni.chooseLocation({
			latitude: opt?.latitude || startPoint.value.latitude,
			longitude: opt?.longitude || startPoint.value.longitude,
			success: function(res) {
				// console.log(res)
				// console.log('位置名称：' + res.name);
				// console.log('详细地址：' + res.address);
				// console.log('纬度：' + res.latitude);
				// console.log('经度：' + res.longitude);
				if (!res.name) {
					return uni.showToast({
						title: '请重新选择位置',
						icon: 'none'
					});
				}
				//设置终点
				endPoint.value = {
					longitude: res.longitude,
					latitude: res.latitude,
					name: res.name,
					address: res.address
				}
				//设置终点标记
				markers.value[1] = {
					id: 2,
					latitude: res.latitude, //纬度
					longitude: res.longitude, //经度
					iconPath: '/static/images/home/endd.png', //显示的图标
					rotate: 0, // 旋转度数
					width: 30, //宽
					height: 30, //高
					title: res.name, //标注点名
					// alpha: 0.5, //透明度
					joinCluster: true,
					customCallout: {
						anchorY: 0,
						anchorX: 0,
						display: "ALWAYS"
					},
				}
		 
				let start = startPoint.value.longitude + ',' + startPoint.value.latitude
				let end = res.longitude + ',' + res.latitude
				//每次选取位置完成后都会默认 10 策略
				flag.value = 10
				//生成规划路线
			    getPlanningRoute(start, end, 10)
			},
			fail: function(info) { //失败回调
				console.log('调取失败')
				console.log(info)
			},
		})
	}
	
	const  getPlanningRoute=(start, end, strategy = 10)=> {
		let that = this
		myAmapFunT.value.getDrivingRoute({
			origin: start,
			destination: end,
			strategy: strategy, //备选方案
			success: function(data) {
				// console.log('所有路径',data)
				if (data.paths && data.paths[0] && data.paths[0].steps) {
					// 默认 10 会 对返回多条路径的方案  按照时间短的
					let goodRouter = data.paths.sort((a, b) => {
						return a.duration - b.duration
					})[0]
	 
					distance.value = (goodRouter.distance * 0.001).toFixed(2);
					duration.value = (goodRouter.duration / 60).toFixed(2);
	 
					// let steps = goodRouter.steps
					// let points = []
					// for (var i = 0; i < steps.length; i++) {
					// 	var poLen = steps[i].polyline.split(';');
					// 	for (var j = 0; j < poLen.length; j++) {
					// 		points.push({
					// 			longitude: parseFloat(poLen[j].split(',')[0]),
					// 			latitude: parseFloat(poLen[j].split(',')[1])
					// 		})
					// 	}
					// }
					that.polyline = [{
						// points: points,
						color: strategy === 10 ? '#0ee532' : strategy === 2 ? '#0742d9' :
							'#ee6b06',
						width: 8,
					}]
				}
				uni.hideLoading();
			},
			fail: function(info) { //失败回调
				console.log('路线规划失败')
				console.log(info)
				uni.hideLoading();
				uni.showToast({
					title: '路线规划失败',
					icon: 'error'
				});
			},
		})
	}
	// const confirmLocation=()=> {
	//       // 确认选择地点
	//       startPoint.value.latitude = selectedLatitude.value;
	//       startPoint.value.longitude = selectedLongitude.value;
	//       showLocationPicker.value = false;
	//       // 这里可以添加将地点信息发送给服务器的代码
	//     }
	//  const    cancelLocation=() =>{
	//     showLocationPicker.value = false;
	//     }
	
	
	
	// const mapReady=(e)=> {
	//       mapCtx.value = uni.createMapContext('map', this);
	//       getRoutePlanning();
	//     }
	//  const   getRoutePlanning=()=> {
	//       var planningUrl = `https://restapi.amap.com/v3/direction/driving?origin=${startPoint.value.longitude},${startPoint.value.latitude}&destination=${endPoint.value.longitude},${endPoint.value.latitude}&key=d4a7ff001e08634bdd5a79e306e3298f`;
	
	//       uni.request({
	//         url: planningUrl,
	//         method: 'GET',
	//         success: (res) => {
	//           if (res.statusCode === 200 && res.data.route) {
	//             const steps = res.data.route.paths[0].steps;
	//             let points = [];
	//             steps.forEach((step) => {
	//               const polyline = step.polyline.split(';');
	//               polyline.forEach((point) => {
	//                 points.push({ latitude: parseFloat(point.split(',')[1]), longitude: parseFloat(point.split(',')[0]) });
	//               });
	//             });
	//             addPolyline(points);
	//           } else {
	//             uni.showToast({
	//               title: '路线规划失败',
	//               icon: 'none'
	//             });
	//           }
	//         },
	//         fail: (err) => {
	//           console.error('请求路线规划失败:', err);
	//         }
	//       });
	//     }
	//     const addPolyline=(points)=> {
	//       if (polyline) {
	//         removePolyline({ id: polyline.value.id });
	//       }
	//       var polylineId = this.mapCtx.addPolyline({
	//         points: points,
	//         color: '#FF0000',
	//         width: 2,
	//         dottedLine: false
	//       });
	//       polyline.value = { id: polylineId };
	//     }

</script>

<style>
.map-container {
  height: 100vh;
}
.location-picker {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 10px;
  text-align: center;
}
/* 样式部分 */
.list-container {
  overflow: hidden; /* 防止背景图片溢出 */
  position: relative; /* 为子元素定位做准备 */
}

.list-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: cover; /* 背景图片覆盖整个容器 */
  background-position: center; /* 背景图片居中显示 */
  z-index: -1; /* 将背景置于内容之下 */
}

.list-item {
  margin: 20px; /* 增加列表项的外边距，使其与背景图片有一定间隔 */
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8); /* 半透明背景，使内容更易读 */
  border-radius: 10px; /* 圆角边框 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

.item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-title {
  font-size: 18px;
  color: #333;
  font-weight: bold;
}

.item-subtitle {
  font-size: 14px;
  color: #666;
}

.send-btn {
			margin-top: 30rpx;
			width: 100%;
			color: white;
			background-color: #ffa602;
			padding: 0 24rpx;
			font-size: 28rpx;
			height: 100px;
			line-height: 100px;
			box-sizing: border-box;
			border-radius: 12rpx;
			text-align: center;
		}

</style>
